
var $ = require('jquery');
var util = require('imutil');
var Backbone = require('backbone');
var Flextext = require('flextext');

var tpl = require('../tpl');
var i18n = require('../i18n');
var servant = require('../i18n/servant');
var bus = require('bus');

var defaults = {
    el: null,
    tmpl: tpl.chat2.chatenter(servant.fuse({}, i18n.chat2))
};

var ChatEnter = function(config){
    this.config = util.extend({}, defaults, config);
    this.elems = {};
    this.__init();
    this._initEvent();
};

ChatEnter.prototype = {
    __init: function(){
        this.elems.$el = $(this.config.el);
        this.elems.$enter = $(this.config.tmpl);
        this.elems.$faceBtn = $(".J-im-icon-face",this.elems.$enter);
        this.elems.$keyBtn = $(".J-im-icon-keyb",this.elems.$enter);
        this.elems.$input = $(".J-im-c-func",this.elems.$enter);
        this.elems.$el.append(this.elems.$enter);
    },
    _initEvent:function(){
        var that = this;
        this.elems.$faceBtn.bind("click",function(e){
            e.preventDefault();
            e.stopPropagation();
            that.showKeyBtn();
        })
        this.elems.$keyBtn.bind("click",function(e){
            e.preventDefault();
            e.stopPropagation();
            that.showFaceBtn();
        })
        this.elems.$input.focus(function(e){
            that.showFaceBtn();
        });

        this.elems.$input.bind("keyup",function(e){
            if (e.keyCode == "13") {//keyCode=13是回车键
                that.enterMsg();
            }
        })

        this.flextext = new Flextext(this.elems.$input[0], {
            onresize: function(h){
                that.trigger('resize');
            }
        });
    },
    addText:function(text,index){
        if(!index || index==""){
            this.elems.$input.val(this.elems.$input.val()+text);
            this.flextext.adjust();
        }

    },
    deleteText: function(content,index){
        var newContent;
        var content1 = content.substr(0,index+1);
        var content2 = content.substr(index+1);
        if(content.charAt(index) != ']'){
            newContent = content1.substr(0,content1.length-1)+content2;
        }else{
            var startIndex = content1.lastIndexOf("[");
            newContent = content1.substr(0,startIndex)+content2;
        }
        this.elems.$input.val(newContent);
        this.flextext.adjust();
    },
    showKeyBtn:function(){
        this.elems.$faceBtn.hide();
        this.elems.$keyBtn.show();
        this.trigger("showKeyBtn");
    },
    showFaceBtn:function(){
        this.elems.$faceBtn.show();
        this.elems.$keyBtn.hide();
        this.trigger("showFaceBtn");
    },enterMsg:function() {
        if(this.elems.$input.val()!=''){
            this.trigger("enterMsg");
        }
    }

};

util.extend(ChatEnter.prototype,Backbone.Events)
module.exports = ChatEnter;